﻿using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using SolidWorks.Interop.swpublished;
using SolidWorksTools;
using System;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;


namespace MechAddin
{
    [Guid("2B54F563-CD07-4024-AE7B-77D0F0D1F058")]
    [ComVisible(true)]
    [SwAddin(Description =DESCRIPTION,LoadAtStartup =true,Title =TITLE)]
    public class SWAddin:SwAddin
    {
        
        private static SldWorks swApp;
        public static SldWorks Sldworks => swApp;
        public const string DESCRIPTION = "更上一层楼啊";
        public const string TITLE = "更上一层楼啊";
        private int AddinId = 0;
        public static string dllPath { get;private set; }
        public bool ConnectToSW(object ThisSW, int Cookie)
        {
            swApp=ThisSW as SldWorks;
            dllPath =Path.GetDirectoryName( Assembly.GetExecutingAssembly().Location);
            AddinId = Cookie;
            swApp.SetAddinCallbackInfo2(0, this, AddinId);
            AddCommands();
            return true;    
        }
        public bool DisconnectFromSW()
        {
            RemoveCommands();
            Marshal.ReleaseComObject(CommandManager);
            CommandManager = null;
            Marshal.ReleaseComObject(swApp);
            swApp = null;
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();

            return true;
        }

        #region 界面
        private enum IDs
        {
            Group0 = ID0,//用于添加菜单功能

            编辑模式,
            Group移动零件,
            移动零件,
            Group零件刷,
            零件刷,

        }
        private const int ID0 = 770010;
        private CommandManager CommandManager { get; set; }
        /// <summary>
        /// 零件模式功能区
        /// </summary>
        private CommandTab CommandTab1 { get; set; }
        /// <summary>
        /// 装配体模式功能区
        /// </summary>
        private CommandTab CommandTab2 { get; set; }
        /// <summary>
        /// 工程图模式功能区
        /// </summary>
        private CommandTab CommandTab3 { get; set; }

        private CommandTabBox CommandTabBox1 { get; set; }
        private CommandTabBox CommandTabBox2 { get; set; }
        private CommandTabBox CommandTabBox3 { get; set; }
        private void AddCommands()
        {
            CommandManager = Sldworks.GetCommandManager(AddinId);
            //添加零件界面工具栏
            CommandTab1 = CommandManager.GetCommandTab(1, TITLE);
            if (CommandTab1 != null) { CommandManager.RemoveCommandTab(CommandTab1); }
            CommandTab1 = CommandManager.AddCommandTab(1, TITLE);
            CommandTabBox1 = CommandTab1.AddCommandTabBox();
            //添加装配体界面工具栏
            CommandTab2 = CommandManager.GetCommandTab(2, TITLE);
            if (CommandTab2 != null)
            {
                CommandManager.RemoveCommandTab(CommandTab2);
            }
            CommandTab2 = CommandManager.AddCommandTab(2, TITLE);
            CommandTabBox2 = CommandTab2.AddCommandTabBox();
            //添加工程图界面工具栏
            CommandTab3 = CommandManager.GetCommandTab(3, TITLE);
            if (CommandTab3 != null)
            {
                CommandManager.RemoveCommandTab(CommandTab3);
            }
            CommandTab3 = CommandManager.AddCommandTab(3, TITLE);
            CommandTabBox3 = CommandTab3.AddCommandTabBox();
            AddCommandsToMenu();
            AddCommand_移动零件();
            AddCommand_零件刷();

        }

        private void AddCommandsToMenu()
        {
            int err = 0;
            CommandGroup CommandGroup0 = CommandManager.CreateCommandGroup2((int)IDs.Group0, TITLE, TITLE, "", -1, true, ref err);
            string name_编辑模式 = "编辑模式";
            CommandGroup0.AddCommandItem2(name_编辑模式, -1, name_编辑模式, name_编辑模式, 0, nameof(Callback_编辑模式), nameof(EnableMethod1), (int)IDs.编辑模式, (int)(swCommandItemType_e.swMenuItem));
            string name_移动零件 = "移动零件";
            CommandGroup0.AddCommandItem2(name_移动零件, -1, name_移动零件, name_移动零件, 0, nameof(Callback_移动零件), nameof(EnableMethod1), (int)IDs.移动零件, (int)(swCommandItemType_e.swMenuItem));
            string name_零件刷 = "零件刷";
            CommandGroup0.AddCommandItem2(name_零件刷, -1, name_零件刷, name_零件刷, 0, nameof(Callback_零件刷), nameof(EnableMethod1), (int)IDs.零件刷, (int)(swCommandItemType_e.swMenuItem));

            CommandGroup0.HasToolbar = false;
            CommandGroup0.HasMenu = true;
            CommandGroup0.Activate();
            var cmdids = new int[] { CommandGroup0.CommandID[0] };
            var textType = new int[] { (int)swCommandTabButtonTextDisplay_e.swCommandTabButton_NoText };
            CommandTabBox3.AddCommands(cmdids, textType);
            CommandTabBox2.AddCommands(cmdids, textType);
            CommandTabBox1.AddCommands(cmdids, textType);
        }
        private void AddCommand_移动零件()
        {
            string path = dllPath;
            string[] icons = new string[6];
            icons[0] = $"{path}\\Resources\\Icons\\移动零件20.PNG";
            icons[1] = $"{path}\\Resources\\Icons\\移动零件32.PNG";
            icons[2] = $"{path}\\Resources\\Icons\\移动零件40.PNG";
            icons[3] = $"{path}\\Resources\\Icons\\移动零件64.PNG";
            icons[4] = $"{path}\\Resources\\Icons\\移动零件96.PNG";
            icons[5] = $"{path}\\Resources\\Icons\\移动零件128.PNG";

            int err = 0;
            CommandGroup CommandGroup0 = CommandManager.CreateCommandGroup2((int)IDs.Group移动零件, TITLE, TITLE, "", -1, true, ref err);
            CommandGroup0.MainIconList = icons;
            CommandGroup0.IconList = icons;
            string name = "移动零件";
            CommandGroup0.AddCommandItem2(name, -1, name, name, 0, nameof(Callback_移动零件), nameof(EnableMethod1), (int)IDs.移动零件, (int)(swCommandItemType_e.swToolbarItem));
            CommandGroup0.HasToolbar = true;
            CommandGroup0.HasMenu = false;
            CommandGroup0.Activate();
            var cmdids = new int[] { CommandGroup0.CommandID[0] };
            var textType = new int[] { (int)swCommandTabButtonTextDisplay_e.swCommandTabButton_TextBelow };
            CommandTabBox2.AddCommands(cmdids, textType);
        }
        private void AddCommand_零件刷()
        {
            string path = dllPath;
            string[] icons = new string[6];
            icons[0] = $"{path}\\Resources\\Icons\\零件刷20.PNG";
            icons[1] = $"{path}\\Resources\\Icons\\零件刷32.PNG";
            icons[2] = $"{path}\\Resources\\Icons\\零件刷40.PNG";
            icons[3] = $"{path}\\Resources\\Icons\\零件刷64.PNG";
            icons[4] = $"{path}\\Resources\\Icons\\零件刷96.PNG";
            icons[5] = $"{path}\\Resources\\Icons\\零件刷128.PNG";

            int err = 0;
            CommandGroup CommandGroup0 = CommandManager.CreateCommandGroup2((int)IDs.Group零件刷, TITLE, TITLE, "", -1, true, ref err);
            CommandGroup0.MainIconList = icons;
            CommandGroup0.IconList = icons;
            string name = "零件刷";
            CommandGroup0.AddCommandItem2(name, -1, name, name, 0, nameof(Callback_零件刷), nameof(EnableMethod1), (int)IDs.零件刷, (int)(swCommandItemType_e.swToolbarItem));
            CommandGroup0.HasToolbar = true;
            CommandGroup0.HasMenu = false;
            CommandGroup0.Activate();
            var cmdids = new int[] { CommandGroup0.CommandID[0] };
            var textType = new int[] { (int)swCommandTabButtonTextDisplay_e.swCommandTabButton_TextBelow };
            CommandTabBox2.AddCommands(cmdids, textType);
        }
        private void RemoveCommands()
        {
            CommandManager.RemoveCommandTab(CommandTab1);
            CommandManager.RemoveCommandTab(CommandTab2);
            CommandManager.RemoveCommandTab(CommandTab3);
        }
        #endregion


        #region 功能区
        public void Callback_编辑模式()
        {
            var sw =new SW控制器();
            sw.编辑模式();
        }
        public void Callback_移动零件()
        {
            var sw=new SW控制器();
            sw.移动零件();
        }

        public void Callback_零件刷()
        {
            var sw = new SW控制器();
            sw.零件刷();
        }

        public int EnableMethod1() => 1;

        #endregion

        #region 注册事件
        [ComRegisterFunctionAttribute]
        public static void RegisterFunction(Type t)
        {
            #region Get Custom Attribute: SwAddinAttribute
            SwAddinAttribute SWattr = null;
            Type type = typeof(SWAddin);
            foreach (System.Attribute attr in type.GetCustomAttributes(false))
            {
                if (attr is SwAddinAttribute)
                {
                    SWattr = attr as SwAddinAttribute;
                    break;
                }
            }

            #endregion Get Custom Attribute: SwAddinAttribute

            try
            {
                Microsoft.Win32.RegistryKey hklm = Microsoft.Win32.Registry.LocalMachine;
                Microsoft.Win32.RegistryKey hkcu = Microsoft.Win32.Registry.CurrentUser;

                string keyname = "SOFTWARE\\SolidWorks\\Addins\\{" + t.GUID.ToString() + "}";
                Microsoft.Win32.RegistryKey addinkey = hklm.CreateSubKey(keyname);
                addinkey.SetValue(null, 0);

                addinkey.SetValue("Description", SWattr.Description);
                addinkey.SetValue("Title", SWattr.Title);

                keyname = "Software\\SolidWorks\\AddInsStartup\\{" + t.GUID.ToString() + "}";
                addinkey = hkcu.CreateSubKey(keyname);
                addinkey.SetValue(null, Convert.ToInt32(SWattr.LoadAtStartup), Microsoft.Win32.RegistryValueKind.DWord);
            }
            catch (System.NullReferenceException nl)
            {

                Console.WriteLine("There was a problem registering this dll: SWattr is null. \n\"" + nl.Message + "\"");
                System.Windows.Forms.MessageBox.Show("There was a problem registering this dll: SWattr is null.\n\"" + nl.Message + "\"");
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.Message);

                System.Windows.Forms.MessageBox.Show("There was a problem registering the function: \n\"" + e.Message + "\"");
            }
        }

        [ComUnregisterFunctionAttribute]
        public static void UnregisterFunction(Type t)
        {
            try
            {
                Microsoft.Win32.RegistryKey hklm = Microsoft.Win32.Registry.LocalMachine;
                Microsoft.Win32.RegistryKey hkcu = Microsoft.Win32.Registry.CurrentUser;

                string keyname = "SOFTWARE\\SolidWorks\\Addins\\{" + t.GUID.ToString() + "}";
                hklm.DeleteSubKey(keyname);

                keyname = "Software\\SolidWorks\\AddInsStartup\\{" + t.GUID.ToString() + "}";
                hkcu.DeleteSubKey(keyname);
            }
            catch (System.NullReferenceException nl)
            {
                Console.WriteLine("There was a problem unregistering this dll: " + nl.Message);
                System.Windows.Forms.MessageBox.Show("There was a problem unregistering this dll: \n\"" + nl.Message + "\"");
            }
            catch (System.Exception e)
            {
                Console.WriteLine("There was a problem unregistering this dll: " + e.Message);
                System.Windows.Forms.MessageBox.Show("There was a problem unregistering this dll: \n\"" + e.Message + "\"");
            }
        }
        #endregion SolidWorks Registration
    }
}
